package com.example.mdc.logback.common.config.mq;


import com.example.mdc.logback.common.config.okhttp.OkHttpLoggingInterceptor;
import jakarta.annotation.PostConstruct;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author :      liu_pc
 * Date:        2023/8/27
 * Description: RocketMQ生产者配置
 * Version:     1.0
 */
@Component
public class RocketMQProducer {

    private final Logger logger = LoggerFactory.getLogger(RocketMQProducer.class);

    @Value("${rocketmq.name-server}")
    private String nameServer;

    @Value("${rocketmq.producer.group}")
    private String producerGroup;

    private DefaultMQProducer producer;

    @PostConstruct
    public void init() throws MQClientException {
        producer = new DefaultMQProducer(producerGroup);
        producer.setNamesrvAddr(nameServer);
        producer.start();
    }

    public void sendMessage(String topic, String message) throws Exception {
        Message msg = new Message(topic, "", message.getBytes(StandardCharsets.UTF_8));
        //tag、keys 可根据具体业务逻辑配置
        msg.setTags("canal");
        msg.setKeys("binlog sync error");
        logger.info("RocketMQ Producer - msg: {}", msg);
        SendResult sendResult = producer.send(msg);
        logger.info("RocketMQ Producer - SendResult: {}", sendResult);
    }
}
